package cn.tedu.mall.order.service.impl;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.pojo.domain.CsmallAuthenticationInfo;
import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.order.mapper.OmsCartMapper;
import cn.tedu.mall.order.service.IOmsCartService;
import cn.tedu.mall.pojo.order.dto.CartAddDTO;
import cn.tedu.mall.pojo.order.dto.CartUpdateDTO;
import cn.tedu.mall.pojo.order.model.OmsCart;
import cn.tedu.mall.pojo.order.vo.CartStandardVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class OmsCartServiceImpl implements IOmsCartService {

    @Autowired
    private OmsCartMapper omsCartMapper;

    @Override
    public void addCart(CartAddDTO cartDTO) {
        //SpringSecurity上下文中获取用户id
        Long userId=getUserId();
        OmsCart omsCart = omsCartMapper.selectExistsCart(userId, cartDTO.getSkuId());

        if(omsCart == null){
            OmsCart newCart = new OmsCart();
            BeanUtils.copyProperties(cartDTO, newCart);
            newCart.setUserId(userId);
            omsCartMapper.saveCart(newCart);
        }else{
            //修改数量
            omsCart.setQuantity(omsCart.getQuantity()+cartDTO.getQuantity());
            omsCartMapper.updateQuantityById(omsCart);
        }


    }


    @Override
    public JsonPage<CartStandardVO> listCarts(Integer page, Integer pageSize) {
        Long userId = getUserId();
        PageHelper.startPage(page, pageSize);
        List<CartStandardVO> carts = omsCartMapper.selectCartByUserId(userId);

        return JsonPage.restPage(new PageInfo<>(carts));
    }

    @Override
    public void removeCart(Long[] ids) {
        // 调用mapper中编写的按数组参数删除购物车信息的方法
        int row=omsCartMapper.deleteCartsByIds(ids);
        if(row==0){
            throw new CoolSharkServiceException(
                    ResponseCode.NOT_FOUND,"您要删除的商品已经删除了");
        }
    }

    @Override
    public void removeAllCarts() {
        Long userId=getUserId();
        int rows=omsCartMapper.deleteCartsByUserId(userId);
        if(rows==0){
            throw new CoolSharkServiceException(
                    ResponseCode.NOT_FOUND,"您的购物车是空的!");
        }
    }

    @Override
    public void removeUserCarts(OmsCart omsCart) {
        // 直接调用删除购物车中商品方法即可
        // 我们电商网站不会因为购物车中商品不存在,就不让用户购买
        // 所以这个删除不判断是否成功,也不抛出异常
        omsCartMapper.deleteCartByUserIdAndSkuId(omsCart);
    }

    @Override
    public void updateQuantity(CartUpdateDTO cartUpdateDTO) {
        // 当前方法参数是CartUpdateDTO,执行修改需要的是OmsCart
        // 所以要先实例化OmsCart对象,并给它赋值
        OmsCart omsCart=new OmsCart();
        // cartUpdateDTO只有id和quantity属性,赋值给omsCart,执行修改的参数齐全了
        BeanUtils.copyProperties(cartUpdateDTO,omsCart);
        // 执行修改
        omsCartMapper.updateQuantityById(omsCart);
    }

    private Long getUserId() {
        return getUserInfo().getId();
    }

    private CsmallAuthenticationInfo getUserInfo() {
        UsernamePasswordAuthenticationToken authenticationToken =
                (UsernamePasswordAuthenticationToken)
                        SecurityContextHolder.getContext().getAuthentication();
        if(authenticationToken == null){
            throw new CoolSharkServiceException(
                    ResponseCode.UNAUTHORIZED, "未登录"
            );
        }
        return (CsmallAuthenticationInfo) authenticationToken.getCredentials();
    }
}
